
//
//  BaiduViewController.m
//  OC注入JS
//
//  Created by YYY on 2018/1/5.
//  Copyright © 2018年 YYY. All rights reserved.
//

#import "BaiduViewController.h"

#import <JavaScriptCore/JavaScriptCore.h>

@interface BaiduViewController () <UIWebViewDelegate>
@property (nonatomic,strong)UIWebView *webView;
@end

@implementation BaiduViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.webView];
    //加载浏览网页
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com/"]];
    [self.webView loadRequest:request];
    // Do any additional setup after loading the view.
}
- (UIWebView *)webView
{
    if (_webView == nil)
    {
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        _webView.delegate = self;
        _webView.scrollView.scrollsToTop = NO;
        _webView.backgroundColor = [UIColor whiteColor];
    }
    return _webView;
}

#pragma mark UIWebView delegate
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    return YES;
}
//加载完成
//webViewDidFinishLoad方法是webView的document已经渲染好后,再去处理这个页面
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    //获取该UIWebView的javascript上下文
    JSContext *jsContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    //在调用前，设置异常回调
    [jsContext setExceptionHandler:^(JSContext *context, JSValue *exception){
        NSLog(@"%@", exception);
    }];
    //这也是一种获取标题的方法。
    JSValue *value = [jsContext evaluateScript:@"document.title"];
    //更新标题
    self.navigationItem.title = value.toString;
    
    //获取JS标题
    //self.title = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    // 在HTML标签都加载完成后,开始处理HTML标签,调用JS,操作document
    [self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('logo').remove();"];
    
    // 自定义editMyLogo函数
    [self.webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
     "script.type = 'text/javascript';"
     "script.text = \"function editMyLogo() { "
     "var logo = document.getElementById('logo');"
     "logo.innerHTML= logo.innerHTML + '这是我自己定义的名字';"
     "var imglist = logo.getElementsByTagName('img');"
     "for (i=0 ; i < imglist.length ; i++ ){"
     "imglist[i].src = 'http://pic.to8to.com/attch/day_160218/20160218_d968438a2434b62ba59dH7q5KEzTS6OH.png';"
     "}"
     "}\";"
     "document.getElementsByTagName('head')[0].appendChild(script);"];
    
    // 执行editMyLogo函数
    [self.webView stringByEvaluatingJavaScriptFromString:@"editMyLogo();"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
